package com.设计模式;

import java.util.Enumeration;
import java.util.Vector;

/*
* 观察者模式很好理解，类似于邮件订阅和 RSS 订阅，当我们浏览一些博客或 wiki 时，经常会看到 RSS 图标，就
这的意思是，当你订阅了该文章，如果后续有更新，会及时通知你。其实，简单来讲就一句话：当一个对象变化时，其
它依赖该对象的对象都会收到通知，并且随着变化！对象之间是一种一对多的关系。
* */
public class 观察者模式
{
    public static void main(String[] args)
    {
        Subject subject = new MySubject();
        subject.add(new Observer1());
        subject.add(new Observer2());
        subject.operation();
    }
}

interface Observer
{
    void update();
}

class Observer1 implements Observer
{
    @Override
    public void update()
    {
        System.out.println("observer1 has received!");
    }
}

class Observer2 implements Observer
{

    @Override
    public void update()
    {
        System.out.println("observer2 has received!");
    }
}

interface Subject
{
    void add(Observer observer);

    void del(Observer observer);

    void notifyObservers();

    void operation();
}

abstract class AbstractSubject implements Subject
{
    private Vector<Observer> vector = new Vector<>();

    public void add(Observer observer)
    {
        vector.add(observer);
    }

    public void del(Observer observer)
    {
        vector.remove(observer);
    }

    public void notifyObservers()
    {
        Enumeration<Observer> enumeration = vector.elements();
        while (enumeration.hasMoreElements())
        {
            enumeration.nextElement().update();
        }
    }
}

class MySubject extends AbstractSubject
{

    @Override
    public void operation()
    {
        System.out.println("update self!");
        notifyObservers();
    }
}

